import json

from flask import Blueprint, request, jsonify, session
from db_config import SQLManager
from json_response import JsonResponse


user_app = Blueprint("user_app", __name__)
db = SQLManager()

@user_app.route("/login", methods=["POST"])  # 添加（单个）
def login():
    data = json.loads(request.data)  # 将json字符串转为dict
    isOk = db.get_one(sql='select ids from users where user_account = %s and user_pwd = %s',
                      args=[data['username'], data['password']])
    if isOk:
        session['uid'] = isOk['ids']
        return JsonResponse.success(msg='登录成功')
    else:
        return JsonResponse.fail(msg='登录失败')


@user_app.route("/all", methods=["GET"])  # 查询（全部）
def all():
    if session.get("uid") is None:
        return JsonResponse.to_dict(JsonResponse(code=101, msg='请登录', data=None))
    result = db.get_list(sql='select * from user')
    return JsonResponse.success(msg='查询成功', data=result)

@user_app.route("/add", methods=["POST"])  # 添加（单个）
def add():
    data = json.loads(request.data)  # 将json字符串转为dict
    isOk = db.modify(sql='insert into user(name,age,sex) values(%s,%s,%s)',
                     args=[data['name'], data['age'], data['sex']])
    return JsonResponse.success(msg='添加成功') if isOk else JsonResponse.fail(msg='添加失败')


@user_app.route("/update", methods=["PUT"])  # 修改（单个）
def update():
    data = json.loads(request.data)  # 将json字符串转为dict
    if 'id' not in data:
        return JsonResponse.fail(msg='需要传入id')
    isOk = db.modify(sql='update user set name=%s,age=%s,sex=%s where id=%s',
                     args=[data['name'], data['age'], data['sex'], data['id']])
    return JsonResponse.success(msg='修改成功') if isOk else JsonResponse.fail(msg='修改失败')


@user_app.route("/delete", methods=["DELETE"])  # 删除（单个）
def delete():
    if 'id' not in request.args:
        return JsonResponse.fail(msg='需要传入id')
    isOk = db.modify(sql='delete from user where id=%s', args=[request.args['id']])
    return JsonResponse.success(msg='删除成功') if isOk else JsonResponse.fail(msg='删除失败')


